package com.xb.loan.util.ocr;

import com.baidu.aip.ocr.AipOcr;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import java.util.HashMap;

public class OcrUtil {
    private static Log log = LogFactory.getLog(OcrUtil.class);

    private static OcrUtil instance;

    //百度云官网获取的 API Key##
    private static String BAIDU_API_KEY="lK6SLRUSLq4b17PjSYNAjXnR";
    //百度云官网获取的 Securet Key
    private static String BAIDU_SECRET_KEY="pC1zqKsm8nNjnuDjmd80Piem6IsLTiWm";
    //百度云官网获取 APP Key ###
    private static String BAIDU_APP_ID="10035933";

    private OcrUtil(){
        FilePro filePro = FilePro.getInstance();

        BAIDU_API_KEY = filePro.getApiKey();
        BAIDU_SECRET_KEY = filePro.getSecretKey();
        BAIDU_APP_ID = filePro.getAppId();
    };

    public static OcrUtil  getInstance(){
        if(instance == null){
            synchronized(OcrUtil.class){
                if(instance==null) {
                    instance = new OcrUtil();
                }
            }
        }
        return instance;
    }

    /**
     * 解析身份证正反面信息，获取解析后的JSON数据
     * @param bytes     文件流
     * @param boo       true身份证正面，false身份证反面
     * @return
     */
    public JSONObject idcardRecognition(byte[] bytes, boolean boo){
        AipOcr client = new AipOcr(BAIDU_APP_ID,BAIDU_API_KEY,BAIDU_SECRET_KEY);
        client.setConnectionTimeoutInMillis(5000);
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("detect_direction","true");
        map.put("accuracy","auto");
        map.put("detect_risk","false");
        JSONObject cardJson = client.idcard(bytes,boo, map);
        return cardJson;
    }

    /**
     * 解析行驶证，获取行驶证上的信息
     * @param bytes 行驶证文件流
     * @return
     */
    public JSONObject vehicleLicenseRecognition(byte[] bytes){
        AipOcr client = new AipOcr(BAIDU_APP_ID,BAIDU_API_KEY,BAIDU_SECRET_KEY);
        client.setConnectionTimeoutInMillis(5000);

        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction","true");
        options.put("accuracy","");

        JSONObject json = client.vehicleLicense(bytes, options);
        return json;
    }


    /**
     * 解析驾驶证，获取驾驶证上的信息
     * @param bytes 驾驶证文件流
     * @return
     */
    public JSONObject driveLicenseRecognition(byte[] bytes){
        AipOcr client = new AipOcr(BAIDU_APP_ID,BAIDU_API_KEY,BAIDU_SECRET_KEY);
        client.setConnectionTimeoutInMillis(5000);

        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction","true");

        JSONObject json = client.drivingLicense(bytes, options);
        return json;
    }

    public static void main(String[] args){
        OcrUtil ou = OcrUtil.getInstance();

    }


}
